package session

import (
	"database/sql"
	"gitee.com/zhendliu/sorm/log"
)

// Begin a transaction
func (s *Session) Begin() (err error) {
	log.Info("transaction begin")
	s.isTx = true
	return
}

// Commit a transaction
func (s *Session) Commit() (err error) {
	log.Info("transaction commit")
	defer func() {
		s.isTx = false
		s.txs = []*sql.Tx{}
		s.txMap = map[*sql.DB]*sql.Tx{}
	}()

	errorResult := []error{}
	for i := range s.txs {
		err = s.txs[i].Commit()
		if err != nil {
			errorResult = append(errorResult, err)
		}
	}
	if len(errorResult) > 0 {
		log.Errorf("transaction commit failed: %v", errorResult)
	}
	return
}

// Rollback a transaction
func (s *Session) Rollback() (err error) {
	log.Info("transaction rollback")
	defer func() {
		s.isTx = false
		s.txs = []*sql.Tx{}
		s.txMap = map[*sql.DB]*sql.Tx{}
	}()
	errorResult := []error{}
	for i := range s.txs {
		err = s.txs[i].Rollback()
		if err != nil {
			errorResult = append(errorResult, err)
		}
	}
	if len(errorResult) > 0 {
		log.Errorf("transaction rollback failed: %v", errorResult)
	}
	return
}
